package com.dongnam.quanly.web.vattuhanghoa;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.DataFormatException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.VatTuHangHoaController;
import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.common.model.KhoHang;
import com.dongnam.quanly.common.model.LoaiVatTuHangHoa;
import com.dongnam.quanly.common.model.VatTuHangHoa;
import com.dongnam.quanly.common.model.enumtype.DonViTinh;
import com.dongnam.quanly.common.model.enumtype.GioiTinh;
import com.dongnam.quanly.common.model.enumtype.TinhChatVTHH;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.danhmuc.phongban.PhongBanBean;
import com.dongnam.quanly.web.util.CsvUtil;
import com.dongnam.quanly.web.util.DateFormatUtil;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "VatTuHangHoaBean")
@SessionScoped
public class VatTuHangHoaBean implements Serializable {

	private static final Logger logger = LoggerFactory.getLogger(VatTuHangHoaBean.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;
	private VatTuHangHoaModel vthhModel;
	private List<VatTuHangHoa> listVthh;

	// for add NhanVien
	private VatTuHangHoa vthh;
	private boolean isEdit = false;
	// for download file
	private StreamedContent file;

	// for load danh sach phong ban
	private VatTuHangHoaController vthhController;

	// for edit phongBan
	private VatTuHangHoa selectedvthh;

	public VatTuHangHoaBean() {
		super();
		vthh = new VatTuHangHoa();
		loadVthh();
		// TODO Auto-generated constructor stub
	}

	public List<VatTuHangHoa> getListVthh() {
		return listVthh;
	}

	public void setListVthh(List<VatTuHangHoa> listVthh) {
		this.listVthh = listVthh;
	}

	public VatTuHangHoaController getVthhController() {

		if (vthhController == null)
			vthhController = new VatTuHangHoaController();
		return vthhController;
	}

	public void setVthhController(VatTuHangHoaController vthhController) {
		this.vthhController = vthhController;
	}

	public void downloadFileCSV() {

		File excelfile = new File("VAT_TU.xls");
		List<VatTuHangHoa> list = getVthhController().findAll();
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(6, 30);
			sheet.setColumnView(7, 30);
			sheet.setColumnView(8, 30);
			sheet.setColumnView(9, 30);
			sheet.setColumnView(10, 30);
			sheet.setColumnView(11, 30);
			sheet.setColumnView(12, 30);
			sheet.setColumnView(13, 30);
			sheet.setColumnView(14, 30);
			sheet.setColumnView(15, 30);
			sheet.setColumnView(16, 30);
			sheet.setColumnView(17, 30);

			sheet.addCell(new Label(0, 0, "Mã hàng hóa", titleformat));
			sheet.addCell(new Label(1, 0, "Tên hàng hóa", titleformat));
			sheet.addCell(new Label(2, 0, "Tính chất", titleformat));
			sheet.addCell(new Label(3, 0, "Loại", titleformat));
			sheet.addCell(new Label(4, 0, "Đơn vị tính", titleformat));
			sheet.addCell(new Label(5, 0, "Thời hạn bảo hành", titleformat));
			sheet.addCell(new Label(6, 0, "Đơn giá mua", titleformat));
			sheet.addCell(new Label(7, 0, "Đơn giá bán", titleformat));
			sheet.addCell(new Label(8, 0, "Nhà cung cấp", titleformat));
			sheet.addCell(new Label(9, 0, "TK chi phí", titleformat));
			sheet.addCell(new Label(10, 0, "CKMH", titleformat));
			sheet.addCell(new Label(11, 0, "Diễn giản khi mua", titleformat));
			sheet.addCell(new Label(12, 0, "Diễn giải khi bán", titleformat));
			sheet.addCell(new Label(13, 0, "Nguồn gốc", titleformat));
			sheet.addCell(new Label(14, 0, "Thuế suất", titleformat));
			sheet.addCell(new Label(15, 0, "Tài khoản kho", titleformat));
			sheet.addCell(new Label(16, 0, "TK doanh thu", titleformat));
			sheet.addCell(new Label(17, 0, "CKBH", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, list.get(i).getMaVTHH(), contentformat));
				sheet.addCell(new Label(1, i + 1, list.get(i).getTenVTHH(), contentformat));

				sheet.addCell(new Label(2, i + 1, list.get(i).getTinhchat().name(), contentformat));
				sheet.addCell(new Label(3, i + 1, list.get(i).getLoaiVTHH(), contentformat));
				sheet.addCell(new Label(4, i + 1, list.get(i).getDonViTinh().name(), contentformat));

				sheet.addCell(new Label(5, i + 1, DateFormatUtil.Date2String("dd-MM-yyyy", list.get(i)
						.getThoiGianBaoHanh()), contentformat));
				sheet.addCell(new Label(6, i + 1, String.valueOf(list.get(i).getDonGiaMua()), contentformat));
				sheet.addCell(new Label(7, i + 1, String.valueOf(list.get(i).getDonGiaBan()), contentformat));
				sheet.addCell(new Label(8, i + 1, list.get(i).getNhaCungCap(), contentformat));
				sheet.addCell(new Label(9, i + 1, list.get(i).gettKChiPhi(), contentformat));

				sheet.addCell(new Label(10, i + 1, String.valueOf(list.get(i).getChietKhauMuaHang()), contentformat));
				sheet.addCell(new Label(11, i + 1, list.get(i).getDienGiaiMua(), contentformat));
				sheet.addCell(new Label(12, i + 1, list.get(i).getDienGiaiBan(), contentformat));
				sheet.addCell(new Label(13, i + 1, list.get(i).getNguonGoc(), contentformat));

				sheet.addCell(new Label(14, i + 1, String.valueOf(list.get(i).getThueSuat()), contentformat));
				sheet.addCell(new Label(15, i + 1, String.valueOf(list.get(i).getTaiKhoanKho()), contentformat));
				sheet.addCell(new Label(16, i + 1, String.valueOf(list.get(i).gettKDoanhThu()), contentformat));
				sheet.addCell(new Label(17, i + 1, String.valueOf(list.get(i).getChietKhauBanHang()), contentformat));

			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv", "VAT_TU.xls", "UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void handleFileUpload(FileUploadEvent event) {

		logger.debug("process upload file ");
		Workbook w;
		boolean rollback = false;
		List<VatTuHangHoa> list = new ArrayList<VatTuHangHoa>();
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines

			for (int row = 1; row < sheet.getRows(); row++) {

				logger.debug("row " + row);
				Cell cell_MaVTHH = sheet.getCell(0, row);
				Cell cell_TenVTHH = sheet.getCell(1, row);
				Cell cell_Tinhchat = sheet.getCell(2, row);
				Cell cell_LoaiVTHH = sheet.getCell(3, row);
				Cell cell_DonViTinh = sheet.getCell(4, row);
				Cell cell_ThoiGianBaoHanh = sheet.getCell(5, row);
				Cell cell_DonGiaMua = sheet.getCell(6, row);
				Cell cell_DonGiaBan = sheet.getCell(7, row);
				Cell cell_MaDoiTac = sheet.getCell(8, row);
				Cell cell_tKChiPhi = sheet.getCell(9, row);
				Cell cell_ChietKhauMuaHang = sheet.getCell(10, row);
				Cell cell_DienGiaiMua = sheet.getCell(11, row);
				Cell cell_DienGiaiBan = sheet.getCell(12, row);
				Cell cell_NguonGoc = sheet.getCell(13, row);
				Cell cell_ThueSuat = sheet.getCell(14, row);
				Cell cell_TaiKhoanKho = sheet.getCell(15, row);
				Cell cell_tKDoanhThu = sheet.getCell(16, row);
				Cell cell_ChietKhauBanHang = sheet.getCell(17, row);

				VatTuHangHoa vt = new VatTuHangHoa();
				vt.setMaVTHH(cell_MaVTHH.getContents());
				vt.setTenVTHH(cell_TenVTHH.getContents());
				vt.setTinhchat(TinhChatVTHH.valueOf(cell_Tinhchat.getContents()));
				vt.setLoaiVTHH(cell_LoaiVTHH.getContents());
				vt.setDonViTinh(DonViTinh.valueOf(cell_DonViTinh.getContents()));
				vt.setThoiGianBaoHanh(DateFormatUtil.String2Date("dd-MM-yyyy", cell_ThoiGianBaoHanh.getContents()));
				vt.setDonGiaMua(Double.parseDouble(cell_DonGiaMua.getContents()));
				vt.setDonGiaBan(Double.parseDouble(cell_DonGiaBan.getContents()));
				vt.setNhaCungCap(cell_MaDoiTac.getContents());
				vt.settKChiPhi(cell_tKChiPhi.getContents());
				vt.setChietKhauMuaHang(Integer.parseInt(cell_ChietKhauMuaHang.getContents()));
				vt.setDienGiaiMua(cell_DienGiaiMua.getContents());
				vt.setDienGiaiBan(cell_DienGiaiBan.getContents());
				vt.setNguonGoc(cell_NguonGoc.getContents());
				vt.setThueSuat(Integer.parseInt(cell_ThueSuat.getContents()));
				vt.setTaiKhoanKho(Integer.parseInt(cell_TaiKhoanKho.getContents()));
				vt.settKDoanhThu(Integer.parseInt(cell_tKDoanhThu.getContents()));
				vt.setChietKhauBanHang(Integer.parseInt(cell_ChietKhauBanHang.getContents()));
				list.add(vt);
			}
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		if (!rollback) {
			getVthhController().batchSaveOrUpdate(list);
		}

		loadVthh();
	}

	public void resetFormAdd() {
		vthh = new VatTuHangHoa();
	}

	public void notifyAdd() {
		isEdit = false;
		resetFormAdd();
	}

	public void notifyEdit(VatTuHangHoa vthh) {
		isEdit = true;
		this.selectedvthh = vthh;
		this.vthh.fillVthh(vthh);
	}

	public void removevthh() {

		if (this.selectedvthh != null) {
			getVthhController().makeTransient(this.selectedvthh);
			loadVthh();
		}

	}

	public void save() {

		RequestContext context = RequestContext.getCurrentInstance();
		try {
			if (isEdit) {
				logger.debug("Edit new NhanVien");

				if (this.selectedvthh != null) {

					getVthhController().makeTransient(this.selectedvthh);

					this.selectedvthh.fillVthh(this.vthh);
					this.selectedvthh.setUpdateBy(userBean.getUser().getUserId());

					getVthhController().makePersistent(this.selectedvthh);
					// change state of parent
					context.addCallbackParam("opSuccess", true);
				}

			} else {

				logger.debug("Add new NhanVien :" + this.vthh.getMaVTHH());
				VatTuHangHoa vthh = new VatTuHangHoa();
				vthh.setCreateBy(userBean.getUser().getUserId());
				vthh.setUpdateBy(userBean.getUser().getUserId());

				vthh.fillVthh(this.vthh);

				getVthhController().makePersistent(vthh);

				context.addCallbackParam("opSuccess", true);

			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			logger.debug("Database error" + e.getMessage());
			context.addCallbackParam("opSuccess", false);

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		loadVthh();

	}

	public void loadVthh() {
		if (vthhModel == null)
			vthhModel = new VatTuHangHoaModel();

		vthhModel.init();

		listVthh = getVthhController().findAll();
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public void reloadPage() {
		loadVthh();
		WebUtil.redirect("/pages/danhmuc/vatTuHangHoa.xhtml");
	}

	public VatTuHangHoaModel getVthhModel() {
		return vthhModel;
	}

	public void setVthhModel(VatTuHangHoaModel vthhModel) {
		this.vthhModel = vthhModel;
	}

	public VatTuHangHoa getVthh() {
		return vthh;
	}

	public void setVthh(VatTuHangHoa vthh) {
		this.vthh = vthh;
	}

	public boolean isEdit() {
		return isEdit;
	}

	public void setEdit(boolean isEdit) {
		this.isEdit = isEdit;
	}

	public VatTuHangHoa getSelectedvthh() {
		return selectedvthh;
	}

	public void setSelectedvthh(VatTuHangHoa selectedvthh) {
		this.selectedvthh = selectedvthh;
	}

	public TinhChatVTHH[] getListTinhChatVTHH() {
		return TinhChatVTHH.values();
	}

	public DonViTinh[] getListDonViTinh() {
		return DonViTinh.values();
	}

}
